package com.ngkj.zmfptback.sys.controller;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcraft.jsch.*;
import com.ngkj.zmfptCommon.common.bean.CommonReslut;
import com.ngkj.zmfptCommon.common.sftp.SFTPChannel;
import com.ngkj.zmfptCommon.common.sftp.SFTPConstants;
import com.ngkj.zmfptCommon.common.util.ResultEnum;
import com.ngkj.zmfptback.sys.bean.UserEntity;
import com.ngkj.zmfptback.sys.config.JwtConfig;
import com.ngkj.zmfptback.sys.service.read.UserReadService;
import com.ngkj.zmfptback.sys.service.write.UserWriteService;
import com.ngkj.zmfptback.sys.util.JwtTokenUtil;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author ChenHN
 * @since 2021/10/25 creation
 **/
@RestController
public class UserInfoController {

    @Resource
    private UserReadService userReadService;

    @Resource
    private UserWriteService userWriteService;

    @Resource
    private SFTPChannel sftpChannel;

    /**
     * 刷新页面获取用户基本信息
     * @param request
     * @return
     */
    @GetMapping("/getUserInfo")
    public CommonReslut getUserInfo(HttpServletRequest request){
        String headerToken = request.getHeader(JwtConfig.tokenHeader);
        if (StringUtils.isEmpty(headerToken)) {
            return new CommonReslut("未登录",300);
        }else{
            //截取jwt前缀
            String token = headerToken.replace(JwtConfig.tokenPrefix, "");
            Map<String, Object> userInfo = JwtTokenUtil.getUserInfo(token);

            UserEntity userByUserId = userReadService.getUserByUserId(userInfo.get("id").toString());
            userInfo.put("username",userByUserId.getUsername());
            userInfo.put("nickname",userByUserId.getNickname());
            userInfo.put("headImage",userByUserId.getHeadImage());
            return new CommonReslut(ResultEnum.ok,userInfo);
        }
    }

    /**
     * 更换头像
     * @param userId
     * @param file
     * @return
     */
    @PostMapping("/myUser/editHeadImage")
    public CommonReslut editHeadImage(String userId, MultipartFile file){
        try {
            Map<String, String> connectParameter = SFTPConstants.getConnectParameter();
            ChannelSftp channel = sftpChannel.getChannel(connectParameter, 60000);
            StringBuilder dir = new StringBuilder("/usr/local/static/images/headImage");
            dir.append( "/"+new SimpleDateFormat("yyyyMMdd").format(new Date()));
            SftpATTRS stat = null;
            try {
                stat = channel.stat(dir.toString());
            } catch (Exception e) {
                // TODO: handle exception
            }
            if (stat == null){
                channel.mkdir(dir.toString());
            }
            String originalFilename = file.getOriginalFilename();
            String filePath = dir + "/" + UUID.randomUUID().toString().replace("-", "") + "_" + originalFilename;
            channel.put(file.getInputStream(), filePath, ChannelSftp.OVERWRITE);
            userWriteService.editHeadImage(userId,filePath.split("/static")[1]);
            return new CommonReslut(ResultEnum.ok);
        } catch (JSchException | SftpException | IOException e) {
            e.printStackTrace();
            return new CommonReslut(ResultEnum.error);
        }

    }

    /**
     * 分页用户信息
     * @param user
     * @param beginTime
     * @param endTime
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/user/getUserList")
    public CommonReslut getUserList(UserEntity user, String beginTime, String endTime,@RequestParam("pageNo") Integer pageNo,@RequestParam("pageSize") Integer pageSize){
        Page<UserEntity> page1 = new Page<>(pageNo,pageSize);
        IPage<UserEntity> page2 = userReadService.getUserList(page1, user, beginTime, endTime);
        return new CommonReslut(ResultEnum.ok,page2);
    }

    /**
     * 更新用户角色
     * @param id
     * @param roleStr
     * @return
     */
    @PutMapping("/user/editUserRole")
    public CommonReslut editUserRole(Integer id,String roleStr){
        try {
            userWriteService.editUserRole(id,roleStr);
            return new CommonReslut(ResultEnum.ok);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonReslut(ResultEnum.error);
        }
    }

    /**
     * 通过id获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/getMyUser")
    public CommonReslut getMyUser(String id){
        try {
            UserEntity myUser = userReadService.getMyUser(id);
            return new CommonReslut(ResultEnum.ok,myUser);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonReslut(ResultEnum.error);
        }
    }

    @GetMapping("/getUserByid")
    public CommonReslut getUserByid(Long id){
        try {
            UserEntity userEntity = userReadService.getUserInfoByRealId(id);
            return new CommonReslut(ResultEnum.ok,userEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonReslut(ResultEnum.error);
        }
    }

    @PutMapping("/editNickname")
    public CommonReslut editNickname(Long id,String nickname){
        try {
            userWriteService.editNickname(id,nickname);
            return new CommonReslut(ResultEnum.ok);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonReslut(ResultEnum.error);
        }
    }

}
